package com.bluemobi.framework.common;

import org.apache.commons.lang.time.DateFormatUtils;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import cn.bluebird.components.id.IdWorker;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@SuppressWarnings("restriction")
public class FileUtil {

    //定义项目根路径
    public final static String basePath = System.getProperty("nbpc.root");

    //专场图片保存地址
    public final static String picPath = "uploadPic/";

    /**
     * 处理上传文件
     *
     * @param file
     * @param rootPath 项目根路径
     * @param filePath 文件路径
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String uploadYardPic(MultipartFile file, String rootPath, String filePath) throws Exception {
        String fileName = null;
        if (!(file.getOriginalFilename() == null || "".equals(file.getOriginalFilename()))) {
            String name = file.getOriginalFilename();
            //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = name.substring(name.lastIndexOf(".") + 1, name.length());
            //对扩展名进行小写转换

            String autoCreatedDateDirByParttern = "yyyy" + File.separatorChar + "MM" + File.separatorChar;
            String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern);//动态目录
            fileName = filePath + autoCreatedDateDir + IdWorker.getId()+ "." + ext.toLowerCase();
            fileName = fileName.replace("\\", "/");
            File f = new File(rootPath + fileName);
            if (!f.exists()) {
                f.mkdirs();
            }
            file.transferTo(f);
        }
        return fileName;
    }


    public static boolean GenerateImage(String imgStr) {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            String imgFilePath = "d://222.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String upLoadEditImg2Server(InputStream in, String ext) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            data = new byte[in.available()];
            in.read(data);
            in.close();
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String base64Str = encoder.encode(data);
            String result = sendPost("images=" + base64Str + "&back=" + ext);
            if(org.apache.commons.lang.StringUtils.isNotEmpty(result)){
                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.getInt("status") == 1) {
                    return jsonObject.getString("url");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String upLoadImgServer(MultipartFile file, String filePath) {
        byte[] data = null;
        InputStream in = null;

        // 读取图片字节数组
        try {
            String name = file.getOriginalFilename();
            //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
            in = file.getInputStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String base64Str = encoder.encode(data);
            String result = sendPost("images=" + base64Str + "&back=" + ext);
            if(org.apache.commons.lang.StringUtils.isNotEmpty(result)){
                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.getInt("status") == 1) {
                    return jsonObject.getString("url");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String upLoadImgServer(InputStream input, String iconPath) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            Image srcImg = ImageIO.read(input);
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            // Graphics g= buffImg.getGraphics();
            Graphics2D g = buffImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 水印图象的路径 水印一般为gif或者png的，这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);
            // 得到Image对象。
            Image img = imgIcon.getImage();
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1));
            // 表示水印图片的位置
            Integer imgWidth=buffImg.getWidth()/2;
            Integer imgHeight=buffImg.getHeight()/2;
            Integer width=imgWidth-(imgWidth/2);
            Integer height=imgHeight-(imgHeight/2);
            g.drawImage(img, width, height,imgWidth,imgHeight,null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            InputStream in;
            // 生成图片
            ImageIO.write(buffImg, "JPG", os);
            in = new ByteArrayInputStream(os.toByteArray());
            byte[] data;
            data = new byte[in.available()];
            in.read(data);
            in.close();
            BASE64Encoder encoder = new BASE64Encoder();
            String base64Str = encoder.encode(data);
            String result = FileUtil.sendPost("images=" + base64Str + "&back=PNG");
            if(org.apache.commons.lang.StringUtils.isNotEmpty(result)){
                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.getInt("status") == 1) {
                    System.out.println(jsonObject.getString("url"));
                    return jsonObject.getString("url");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static void removeImage(String imageName) {
        File file = new File(imageName);//这里只能指定删除一个文件,
        //如果想要实现删除全部内容要怎么做?
        file.delete();
    }

    public static String sendPost(String param) {
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL("http://up.intco.cn/upload/image/upImg");
            // 打开和URL之间的连接
            HttpURLConnection httpConn = (HttpURLConnection) realUrl.openConnection();
            httpConn.setDoOutput(true);// 使用 URL 连接进行输出
            httpConn.setDoInput(true);// 使用 URL 连接进行输入
            httpConn.setUseCaches(false);// 忽略缓存
            httpConn.setRequestMethod("POST");// 设置URL请求方法
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            OutputStream outputStream = httpConn.getOutputStream();
            outputStream.write(param.getBytes());
            outputStream.close();
            BufferedReader in1 = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
            String inputLine;
            while ((inputLine = in1.readLine()) != null) {
                result += inputLine;
            }
            in1.close();
            return result;
            /*
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            //out = new PrintWriter(conn.getOutputStream());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // utf-8编码
            // 发送请求参数
            byte[] b = param.toString().getBytes();
            conn.getOutputStream().write(b, 0, b.length);
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += new String(line.getBytes(), "utf-8");
                ;
            }*/
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void  mkdir(String filePath){
        filePath=filePath.replace("\\","/");
        String paths[] = filePath.split("/");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 1; i++) {
            try {
                dir = dir + "/" + paths[i + 1];
                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    dirFile.mkdir();
                    System.out.println("创建目录为：" + dir);
                }
            } catch (Exception err) {
                System.err.println("ELS - Chart : 文件夹创建发生异常");
            }
        }
    }

}
